package org.jground.rx.ui.zk.docu;

import java.io.FileInputStream;
import java.io.FileNotFoundException;

import org.apache.commons.io.FilenameUtils;
import org.jground.dbfs.IDBFile;
import org.jground.rx.RXSystem;
import org.jground.rx.docu.DocuUtils;
import org.jground.rx.ui.zk.UIMessageboxUtils;
import org.jground.rx.ui.zk.viewControl.UIAttributeViewControlFactory;
import org.jground.util.IOUtils;
import org.zkoss.image.AImage;
import org.zkoss.zul.Filedownload;
import org.zkoss.zul.Toolbarbutton;

public class UIDocuUtils extends org.jground.rx.docu.DocuUtils  {



    public static void setPictureLink(Toolbarbutton docuLink, long oid, int resize, String filename) {
        try {
            AImage aimage = getImage(oid, filename);
            docuLink.setLabel("");
            docuLink.setImageContent(aimage);
        } catch (Exception e) {
            UIAttributeControlDocu.logger.error(e, e);
        }
    }

    public static AImage getImage(long oid, int resize, String filename) {
    	IDBFile file = DocuUtils.getImageFile(oid, resize, filename);
        try {
            return new AImage(file.getName(), RXSystem.getInstance().getFileService().getData(file));
        } catch (Exception e) {
            UIAttributeControlDocu.logger.error(e, e);
        }
        return null;
    }

    public static AImage getImage(long oid, String filename) {
    	IDBFile file = DocuUtils.getFile(oid, filename);
        try {
            return new AImage(file.getName(), RXSystem.getInstance().getFileService().getData(file));
        } catch (Exception e) {
            UIAttributeControlDocu.logger.error(e, e);
        }
        return null;
    }

    public static void download(String filePath) {
        FileInputStream in = null;
        String filename = FilenameUtils.getName(filePath);
        try {
            Filedownload.save(new FileInputStream(filePath), null, filename);
        } catch (FileNotFoundException e) {
            UIMessageboxUtils.showInfoMessage("Could not find or download file.", "Sorry, the file " + filename
                    + " could not be downloaded!");
        } finally {
            IOUtils.closeQuietly(in);
        }
    }

    public static void registerUI() {
        UIAttributeViewControlFactory.registerControlFactory(fileUpload, new UIAttributeControlDocu());
        UIAttributeViewControlFactory.registerControlFactory(pictureUpload, new UIAttributeControlDocu());
        UIAttributeViewControlFactory.registerViewFactory(docuLink, new UIAttributeViewDocu());
        UIAttributeViewControlFactory.registerViewFactory(picture, new UIAttributeViewDocu());
    }
}
